package com.wanghang89.gmail.util.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;

public class AddPreparedStatementCallback implements PreparedStatementCallback<Long>
{
	private Object[] params;
	private final static Logger LOGGER =Logger.getLogger(AddPreparedStatementCallback.class);	
	
	public AddPreparedStatementCallback(Object[] params)
	{
		this.params = params;
	}

	@Override
	public Long doInPreparedStatement(PreparedStatement pstmt)
			throws SQLException, DataAccessException {
		ResultSet rs = null;
		if (params!=null&&params.length>0) {
			int length = params.length;
			for (int i = 0; i <length; i++) {
				pstmt.setObject(i+1,params[i]);
			}
		}
		pstmt.executeUpdate();
		rs = pstmt.getGeneratedKeys();
		Long id = rs.next()?rs.getLong(1):-1l;
		LOGGER.debug("method add , id:"+id);
		DbUtils.closeResultSet(rs);
		params = null;
		return id;
	}
	
}
